package response

import (
	"errors"
	"gitee.com/z930255076/go-ext/utils"
	"github.com/gofiber/fiber/v2"
	"os"
)

type Debug struct {
	Runtime string      `json:"runtime"`
	Sql     interface{} `json:"sql"`
	Http    interface{} `json:"http"`
}

func Success(c *fiber.Ctx, data interface{}) error {
	result := make(map[string]interface{})
	result["code"] = 1
	result["msg"] = "成功"
	result["data"] = data

	if os.Getenv("DEBUG") == "true" {
		trace := utils.TE.GetDebugData()
		result["debug"] = Debug{
			Sql:     trace.Sql,
			Runtime: trace.Execute,
			Http:    trace.Http,
		}
	}

	return c.JSON(result)
}

func Error(c *fiber.Ctx, err error) error {
	var e *fiber.Error
	_ = errors.As(err, &e)

	result := make(map[string]interface{})
	result["code"] = e.Code
	result["msg"] = err.Error()
	result["data"] = nil

	if os.Getenv("DEBUG") == "true" {
		trace := utils.TE.GetDebugData()
		result["debug"] = Debug{
			Sql:     trace.Sql,
			Runtime: trace.Execute,
			Http:    trace.Http,
		}
	}

	return c.JSON(result)
}
